/// 内容检测器 - 通过文件头检测真实格式
pub struct ContentDetector;

impl ContentDetector {
    /// 检测文件内容的真实格式
    pub fn detect_real_format(data: &[u8]) -> &'static str {
        if data.len() < 8 {
            return "unknown";
        }

        // JPEG文件头检测
        if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
            return "jpeg";
        }

        // PNG文件头检测
        if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
            return "png";
        }

        // TS文件头检测 (MPEG-TS同步字节 0x47)
        if data[0] == 0x47 {
            // 检查是否为有效的TS包（每188字节一个包，都以0x47开头）
            if data.len() >= 188 && data[188] == 0x47 {
                return "ts";
            }
            if data.len() >= 376 && data[376] == 0x47 {
                return "ts";
            }
            return "ts";
        }

        // MP4文件头检测
        if data.len() >= 8 {
            let ftyp = &data[4..8];
            if ftyp == b"ftyp" {
                return "mp4";
            }
        }

        // M4S文件头检测（类似MP4）
        if data.len() >= 12 {
            let styp = &data[4..8];
            if styp == b"styp" {
                return "m4s";
            }
        }

        "unknown"
    }

    /// 检测是否为视频格式
    pub fn is_video_format(format: &str) -> bool {
        matches!(format, "ts" | "mp4" | "m4s")
    }

    /// 检测是否为图片格式
    pub fn is_image_format(format: &str) -> bool {
        matches!(format, "jpeg" | "png")
    }

    /// 获取格式描述
    pub fn get_format_description(format: &str) -> &'static str {
        match format {
            "jpeg" => "JPEG图片",
            "png" => "PNG图片", 
            "ts" => "MPEG-TS视频流",
            "mp4" => "MP4视频文件",
            "m4s" => "MP4分片文件",
            _ => "未知格式"
        }
    }

    /// 分析内容不匹配的情况
    pub fn analyze_format_mismatch(filename_ext: &str, real_format: &str) -> String {
        match (filename_ext.to_lowercase().as_str(), real_format) {
            ("jpeg" | "jpg", "ts") => {
                "⚠️  检测到格式伪装：文件扩展名为JPEG，但实际内容是TS视频流".to_string()
            }
            ("jpeg" | "jpg", "mp4") => {
                "⚠️  检测到格式伪装：文件扩展名为JPEG，但实际内容是MP4视频".to_string()
            }
            ("ts", "jpeg") => {
                "⚠️  检测到格式不匹配：文件扩展名为TS，但实际内容是JPEG图片".to_string()
            }
            ("mp4", "jpeg") => {
                "⚠️  检测到格式不匹配：文件扩展名为MP4，但实际内容是JPEG图片".to_string()
            }
            _ if filename_ext != real_format => {
                format!("⚠️  文件扩展名({filename_ext})与实际内容({real_format})不匹配")
            }
            _ => {
                format!("✅ 文件格式一致：{real_format}")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_jpeg() {
        let jpeg_header = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46];
        assert_eq!(ContentDetector::detect_real_format(&jpeg_header), "jpeg");
    }

    #[test]
    fn test_detect_png() {
        let png_header = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        assert_eq!(ContentDetector::detect_real_format(&png_header), "png");
    }

    #[test]
    fn test_detect_ts() {
        // 模拟TS包（188字节，每个包以0x47开头）
        let mut ts_data = vec![0x47; 188];
        ts_data.extend_from_slice(&[0x47; 188]);
        assert_eq!(ContentDetector::detect_real_format(&ts_data), "ts");
    }

    #[test]
    fn test_detect_mp4() {
        let mp4_header = b"\x00\x00\x00\x20ftypiso4";
        assert_eq!(ContentDetector::detect_real_format(mp4_header), "mp4");
    }

    #[test]
    fn test_format_classification() {
        assert!(ContentDetector::is_video_format("ts"));
        assert!(ContentDetector::is_video_format("mp4"));
        assert!(ContentDetector::is_image_format("jpeg"));
        assert!(ContentDetector::is_image_format("png"));
        
        assert!(!ContentDetector::is_video_format("jpeg"));
        assert!(!ContentDetector::is_image_format("ts"));
    }

    #[test]
    fn test_format_mismatch_analysis() {
        let result = ContentDetector::analyze_format_mismatch("jpeg", "ts");
        assert!(result.contains("格式伪装"));
        assert!(result.contains("JPEG"));
        assert!(result.contains("TS"));
    }
}